package com.lds.config.center.client.listener;

import com.google.common.collect.Multimap;
import com.lds.config.center.client.listener.Annotation.BeanField;
import com.lds.config.center.client.listener.Annotation.DefaultItemChangeEventListenerBeanPostProcessor;
import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Objects;

public class DefaultItemChangeEventListener implements ItemChangeEventListener {
    @Override
    public void onChange(ItemChangeEvent event) {
        // @value
        valueChange(event);

        // @configurationProperties
        configurationPropertiesChange(event);
    }

    private void valueChange(ItemChangeEvent event) {

    }

    private void configurationPropertiesChange(ItemChangeEvent event) {
        Multimap<String, BeanField> beanFieldMap = DefaultItemChangeEventListenerBeanPostProcessor.getBeanFieldMap();

        event.getItemMap().forEach((key, value) -> {
            Collection<BeanField> beanFields = beanFieldMap.get(key);
            if (CollectionUtils.isNotEmpty(beanFields)) {
                beanFields.forEach(beanField -> {
                    try {
                        Field field = beanField.getField();
                        field.setAccessible(true);
                        Object o = field.get(beanField.getBean());
                        if (!Objects.equals(o, value)) {
                            field.set(beanField.getBean(), value);
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        });
    }
}
